// 商家统计分析主页面
<template>
  <div class="statistics-dashboard">
    <!-- 统计卡片 -->
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon">
            <el-icon><ShoppingCart /></el-icon>
          </div>
          <div class="stat-info">
            <h3>总订单数</h3>
            <p class="stat-value">{{ salesData.totalOrders || 0 }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon">
            <el-icon><ShoppingBag /></el-icon>
          </div>
          <div class="stat-info">
            <h3>总销量</h3>
            <p class="stat-value">{{ salesData.totalSales || 0 }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon">
            <el-icon><Sell /></el-icon>
          </div>
          <div class="stat-info">
            <h3>总收入</h3>
            <p class="stat-value">¥{{ formatNumber(salesData.totalRevenue || 0) }}</p>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="stat-card">
          <div class="stat-icon">
            <el-icon><DataLine /></el-icon>
          </div>
          <div class="stat-info">
            <h3>平均订单金额</h3>
            <p class="stat-value">¥{{ formatNumber(salesData.averageOrderValue || 0) }}</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 销售趋势图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="24">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>销售趋势</span>
              <el-radio-group v-model="timeRange" size="small" @change="handleTimeRangeChange">
                <el-radio-button label="week">近7天</el-radio-button>
                <el-radio-button label="month">近30天</el-radio-button>
                <el-radio-button label="quarter">近90天</el-radio-button>
              </el-radio-group>
            </div>
          </template>
          <div class="chart-container">
            <v-chart :option="salesTrendOption" autoresize />
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 热销商品 -->
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="table-card">
          <template #header>
            <div class="card-header">
              <span>热销商品TOP5</span>
              <el-button type="primary" link @click="refreshHotProducts">
                <el-icon><Refresh /></el-icon> 刷新
              </el-button>
            </div>
          </template>
          <el-table :data="hotProducts" stripe style="width: 100%">
            <el-table-column type="index" label="排名" width="80" />
            <el-table-column prop="productName" label="商品名称" min-width="180" show-overflow-tooltip />
            <el-table-column prop="orderCount" label="订单数" width="100" sortable />
            <el-table-column prop="totalQuantity" label="销量" width="100" sortable />
            <el-table-column prop="totalAmount" label="销售额" width="120" sortable>
              <template #default="{ row }">
                ¥{{ formatNumber(row.totalAmount) }}
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>

    <!-- 子路由内容 -->
    <router-view v-if="$route.path !== '/merchant/statistics'" />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { use } from 'echarts/core'
import { CanvasRenderer } from 'echarts/renderers'
import { LineChart, BarChart } from 'echarts/charts'
import {
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
} from 'echarts/components'
import VChart from 'vue-echarts'
import {
  ShoppingCart,
  ShoppingBag,
  Sell,
  DataLine,
  Refresh
} from '@element-plus/icons-vue'
import { 
  getMerchantProductCount,
  getMerchantTodayOrderStats,
  getMyMerchantSalesStatistics,
  getMerchantSalesTrend,
  getMerchantHotProducts
} from '@/api/statistics'

// 注册必需的组件
use([
  CanvasRenderer,
  LineChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
  GridComponent
])

// 数据定义
const timeRange = ref('week')
const productStats = ref({})
const todayStats = ref({})
const hotProducts = ref([])
const salesData = ref({
  totalOrders: 0,
  totalSales: 0,
  totalRevenue: 0,
  averageOrderValue: 0,
  monthlySales: 0,
  dates: [],
  amounts: [],
  orders: []
})

// 获取商品统计
const fetchProductStats = async () => {
  try {
    const res = await getMerchantProductCount()
    if (res.code === 200) {
      productStats.value = res.data
    }
  } catch (error) {
    console.error('获取商品统计失败:', error)
  }
}

// 获取今日订单统计
const fetchTodayStats = async () => {
  try {
    const res = await getMerchantTodayOrderStats()
    if (res.code === 200) {
      todayStats.value = res.data
    }
  } catch (error) {
    console.error('获取今日订单统计失败:', error)
  }
}

// 获取销售统计
const fetchSalesStats = async () => {
  try {
    const res = await getMyMerchantSalesStatistics()
    if (res.code === 200) {
      salesData.value = {
        ...salesData.value,
        totalOrders: res.data.totalOrders || 0,
        totalSales: res.data.totalSales || 0,
        totalRevenue: res.data.totalRevenue || 0,
        averageOrderValue: res.data.averageOrderValue || 0,
        monthlySales: res.data.monthlySales || 0
      }
    }
  } catch (error) {
    console.error('获取销售统计失败:', error)
  }
}

// 获取销售趋势数据
const fetchSalesTrend = async () => {
  try {
    const now = new Date()
    let startTime, endTime
    
    switch (timeRange.value) {
      case 'week':
        startTime = new Date(now - 7 * 24 * 60 * 60 * 1000)
        endTime = now
        break
      case 'month':
        startTime = new Date(now - 30 * 24 * 60 * 60 * 1000)
        endTime = now
        break
      case 'quarter':
        startTime = new Date(now - 90 * 24 * 60 * 60 * 1000)
        endTime = now
        break
    }
    
    const res = await getMerchantSalesTrend(
      startTime.toISOString(),
      endTime.toISOString(),
      timeRange.value === 'month' ? 'month' : 'day'
    )
    
    if (res.code === 200 && res.data) {
      salesData.value = {
        ...salesData.value,
        dates: res.data.map(item => item.date),
        amounts: res.data.map(item => item.salesAmount),
        orders: res.data.map(item => item.orderCount)
      }
    }
  } catch (error) {
    console.error('获取销售趋势失败:', error)
  }
}

// 获取热销商品
const fetchHotProducts = async () => {
  try {
    const res = await getMerchantHotProducts()
    if (res.code === 200) {
      hotProducts.value = res.data || []
    }
  } catch (error) {
    console.error('获取热销商品失败:', error)
  }
}

// 刷新热销商品
const refreshHotProducts = () => {
  fetchHotProducts()
}

// 格式化日期
const formatChartDate = (dateArray) => {
  if (!dateArray || !Array.isArray(dateArray)) return ''
  const [year, month, day] = dateArray
  return `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`
}

// 销售趋势图表配置
const salesTrendOption = computed(() => ({
  title: {
    text: '销售趋势'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'cross',
      label: {
        backgroundColor: '#6a7985'
      }
    }
  },
  legend: {
    data: ['销售额', '订单数']
  },
  grid: {
    left: '3%',
    right: '4%',
    bottom: '3%',
    containLabel: true
  },
  xAxis: {
    type: 'category',
    boundaryGap: false,
    data: salesData.value.dates.map(date => formatChartDate(date))
  },
  yAxis: [
    {
      type: 'value',
      name: '销售额',
      axisLabel: {
        formatter: '¥{value}'
      }
    },
    {
      type: 'value',
      name: '订单数',
      position: 'right'
    }
  ],
  series: [
    {
      name: '销售额',
      type: 'line',
      smooth: true,
      data: salesData.value.amounts,
      areaStyle: {
        opacity: 0.3
      }
    },
    {
      name: '订单数',
      type: 'line',
      yAxisIndex: 1,
      smooth: true,
      data: salesData.value.orders,
      areaStyle: {
        opacity: 0.3
      }
    }
  ]
}))

// 处理时间范围变化
const handleTimeRangeChange = () => {
  fetchSalesTrend()
}

// 格式化数字
const formatNumber = (num) => {
  return num.toLocaleString('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  })
}

onMounted(() => {
  fetchProductStats()
  fetchTodayStats()
  fetchSalesStats()
  fetchSalesTrend()
  fetchHotProducts()
})
</script>

<style scoped>
.statistics-dashboard {
  padding: 20px;
}

.stat-card {
  height: 160px;
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  font-size: 48px;
  color: #409EFF;
  margin-bottom: 16px;
}

.stat-info h3 {
  margin: 0 0 8px;
  font-size: 18px;
  color: #606266;
}

.stat-value {
  margin: 0;
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.chart-row {
  margin: 20px 0;
}

.chart-card,
.table-card {
  margin-bottom: 20px;
}

.chart-container {
  height: 400px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}
</style>
